<template>
  <div class="aviation-content">
    <CustomSwiper :data="SwiperData"></CustomSwiper>
    <Container padding-left="4.2708vw" padding-right="4.2708vw" padding-top="0" padding-bottom="0">
      <NavPanel :activeId="navActiveId" :data="navPanelData" @item-click="navPanelItemClick" />
      <template v-if="!listTableVisible">
        <InputAddressSearch country v-model="courseListParams.course_ku_title"
          v-model:countryValue="courseListParams.course_address_id" @search="inputSearch" @select-city="citySelect">
        </InputAddressSearch>
        <div class="outer-course-box" v-for="(item, index) in courseList" :key="index">
          <Course :data="item"></Course>
        </div>
        <ShowMore visible pc scroll :fetching="courseListFetchData" v-model:currentPage="courseListCurrentPage"
          :totalCount="courseListTotalPage" @load-more="useAviationCourseData" />
      </template>
      <template v-else>
        <Container padding-left="13.5417vw" padding-top="0" padding-bottom="0" padding-right="13.5417vw"
          class="aviation-inner-container">
          <TableCollapse gapTop :data="listTableList" @clickEndCol="clickEndCol" />
          <ShowMore v-model:currentPage="listTableParams.page" v-model:pageSize="listTableParams.rows"
            :totalCount="listTableParams.total" @change="getSimpleCourse"></ShowMore>
        </Container>
      </template>
    </Container>
    <DialogService type_key="simple_course" :submit_id="submit_id" ref="dialogServiceRef"></DialogService>
    <DialogMobileService type_key="simple_course" :submit_id="submit_id" ref="dialogMobileServiceRef">
    </DialogMobileService>
  </div>
</template>

<script setup lang="ts">
import {
  reactive,
  ref,
  watch,
  onMounted,
  getCurrentInstance,
  nextTick,
  onBeforeUnmount,
} from "vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import { useCacheStore, useGlobalStore, useMemberStore } from "../../../store";
import {
  postCourseCategory,
  postCourseSimpleList,
} from "../../../api/aviation";
import { postCouseList } from "../../../api/aviation";
import CustomSwiper from "./Swiper.vue";
import Course from "./Course.vue";

const memberStore = useMemberStore();
const route = useRoute();
const $t = getCurrentInstance()!.appContext.config.globalProperties.$t;

let navPanelData = ref();
let navActiveId = ref();
const navCurrentIndex = ref(0);
const getNavPanelData = async () => {
  let res = await postCourseCategory();
  navPanelData.value = res.data.map((item) => {
    return {
      ...item,
      label: item.title,
      value: item.id,
    };
  });
  let cat_id = route.query.cat_id;
  if (cat_id) {
    navActiveId.value = cat_id;
    navCurrentIndex.value = navPanelData.value.findIndex(
      (item) => item.value == cat_id
    );
  }
  resetDataVisible();
};

// 监听 nav-panel 事件回调
const navPanelItemClick = (item: any, index: number) => {
  navActiveId.value = item.value;
  navCurrentIndex.value = index;
  resetDataVisible();
};

// 普通课程提交咨询
const dialogServiceRef = ref();
const dialogMobileServiceRef = ref();
const submit_id = ref();
const clickEndCol = (item: any) => {
  if (!memberStore.profile) return message.warning($t("message.wait_login"));
  submit_id.value = item.id;
  nextTick(() => {
    if (isMobile()) {
      dialogMobileServiceRef.value.show();
    } else {
      dialogServiceRef.value.show();
    }
  });
};

/**
 * 获取课程数据
 */

const courseListTotalPage = ref(0);
const courseListCurrentPage = ref(0);
const hasCourseListData = ref(false);
const courseListFetchData = ref(false);
let courseList = ref<any[]>([""]);
let courseListParams = reactive({
  course_cat_id: "",
  course_address_id: "",
  course_ku_title: "",
  page: 1,
  rows: 16,
});

const inputSearch = () => {
  courseListParams.page = 1;
  courseListTotalPage.value = 0;
  courseListFetchData.value = false;
  courseList.value = [""];
  hasCourseListData.value = false;
  useAviationCourseData();
};

// pc-城市选择
const citySelect = () => {
  inputSearch();
};

const useAviationCourseData = async () => {
  if (courseListFetchData.value) return;
  if (Array.isArray(courseList.value[0])) {
    courseList.value.push("");
  }
  courseListParams.course_cat_id = navPanelData.value[navCurrentIndex.value].id;
  // 加载数据中...
  courseListFetchData.value = true;
  let res = await postCouseList(courseListParams);

  if (res.code === 200) {
    courseList.value[courseListParams.page - 1] = res.data.data;
    courseListFetchData.value = false;
    courseListParams.page++;
    courseListCurrentPage.value = res.data.current_page;
    if (!hasCourseListData.value) hasCourseListData.value = true;
    if (!courseListTotalPage.value) {
      courseListTotalPage.value = res.data.last_page;
    }
  }
};

// 轮播数据
const SwiperData = ref();
const getSwiperData = async () => {
  try {
    let res = await postCouseList({ rows: 16, is_recommend: 2, page: 1 });
    if (res.code == 200) {
      SwiperData.value = res.data.data;
    } else {
      SwiperData.value = [];
    }
  } catch (error) {
    SwiperData.value = [];
  }
  // 设置缓存
  // if (!SwiperData.value) {
  //   SwiperData.value = res.data.data.slice(0, swiper_count);
  //   cacheStore.aviationData.swiper = SwiperData.value;
  // }
};

const resetDataVisible = () => {
  let list_type_id = navPanelData.value[navCurrentIndex.value].type_id;
  navActiveId.value = navPanelData.value[navCurrentIndex.value].value;
  if (list_type_id != null && list_type_id == 2) {
    listTableVisible.value = true;
    listTableParams.value.page = 1;
    getSimpleCourse();
  } else {
    hasCourseListData.value = false;
    courseListParams.page = 1;
    courseListTotalPage.value = 0;
    courseList.value = [""];
    listTableVisible.value = false;
    courseListParams.course_address_id = "";
    courseListParams.course_ku_title = "";
    if (hasCourseListData.value) return;
    useAviationCourseData();
  }
};

// 获取普通课程数据
const listTableList = ref<{
  headers: any[];
  items?: any[] | undefined;
}>({
  headers: [],
  items: undefined,
});

const getSimpleCourseHeaders = () => {
  listTableList.value.headers = [
    {
      title: "table.aviation.col_1",
      key: "course_name",
      width: "16.6667vw",
    },
    {
      title: "table.aviation.col_2",
      key: "course_price",
      width: "100%",
    },
  ];
};

const resetPageSize = () => {
  if (isMobile()) {
    courseListParams.rows = 8;
  } else {
    courseListParams.rows = 16;
  }
};

getSimpleCourseHeaders();

onMounted(async () => {
  await nextTick();
  getNavPanelData();
  getSwiperData();
  resetPageSize();
  window.addEventListener("resize", resetPageSize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resetPageSize);
});

const listTableVisible = ref(false);
const listTableParams = ref({
  cat_id: "",
  page: 1,
  rows: 10,
  total: 0,
});
const getSimpleCourse = async () => {
  let cat_id = navPanelData.value[navCurrentIndex.value].id;
  // 读取缓存
  // let _data = cacheStore.aviationData.tables.find(
  //   (item) => item.id == cat_id
  // )?.data;
  // if (_data) {
  //   listTableList.value.items = _data;
  //   return;
  // }
  listTableParams.value.cat_id = cat_id;
  listTableList.value.items = undefined;
  const { total, ...params } = listTableParams.value;
  let res = await postCourseSimpleList(params);
  if (res.code == 200) {
    let items = res.data.data.map((item) => {
      return {
        id: item.id,
        col_1: {
          value: item.course_no,
        },
        col_2: {
          value: item.title,
        },
        details: item.content,
      };
    });
    listTableList.value.items = items;
    listTableParams.value.total = res.data.total;
    // 设置缓存
    // cacheStore.aviationData.tables.push({
    //   id: cat_id,
    //   data: items,
    // });
  }
};
</script>
<style scoped lang="less">
.outer-course-box {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

@media screen and (max-width: 768px) {
  .mobile-sticky {
    position: sticky;
    top: var(--yd-header-height);
  }

  .outer-course-box {
    margin-bottom: 61px;
  }
}
</style>
